package com.ip.user.service.impl;

import com.ip.user.models.service.SysUserService;
import com.ip.user.models.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 注意：这里我们不能直接使用sysUserService.getUserByUserName(username)
        // 因为UserVO不包含密码信息，而UserDetails需要密码
        // 我们需要创建一个特殊的查询方法来获取包含密码的用户信息
        // 但在当前架构中，我们可以创建一个没有实际密码的UserDetails对象
        // 真正的密码验证应该在登录过程中完成
        
        UserVO sysUser = sysUserService.getUserByUserName(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }

        // 检查用户状态
        if (sysUser.getUserStatus() != 1) {
            throw new UsernameNotFoundException("User is disabled: " + username);
        }

        // 设置权限，管理员有特殊权限
        String role = "USER";
        if (sysUser.getIsStudentAdmin() == 1) {
            role = "ADMIN";
        }

        // 注意：在实际应用中，我们不应将真实密码存储在UserDetails中
        // 这里我们使用一个占位符，因为认证应该在登录时完成
        return new User(
                sysUser.getUserName(),
                "", // 不存储真实密码
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role))
        );
    }
}